import React, { useState, useEffect } from 'react';
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, Legend } from 'recharts';
import { Expense, CATEGORY_CONFIG, StatisticsData } from '../types';

interface StatisticsProps {
  expenses: Expense[];
}

const Statistics: React.FC<StatisticsProps> = ({ expenses }) => {
  const [statisticsData, setStatisticsData] = useState<StatisticsData[]>([]);
  const [totalAmount, setTotalAmount] = useState<number>(0);
  
  useEffect(() => {
    if (expenses.length === 0) {
      setStatisticsData([]);
      setTotalAmount(0);
      return;
    }
    
    // 计算总金额
    const total = expenses.reduce((sum, expense) => sum + expense.amount, 0);
    setTotalAmount(total);
    
    // 按类别统计
    const categoryTotals: Record<string, number> = {};
    
    expenses.forEach(expense => {
      if (!categoryTotals[expense.category]) {
        categoryTotals[expense.category] = 0;
      }
      categoryTotals[expense.category] += expense.amount;
    });
    
    // 转换为图表数据格式
    const data = Object.entries(categoryTotals).map(([category, amount]) => ({
      category,
      amount,
      percentage: (amount / total) * 100,
      color: CATEGORY_CONFIG[category as keyof typeof CATEGORY_CONFIG]?.color || 'bg-gray-500'
    }));
    
    // 按金额降序排序
    data.sort((a, b) => b.amount - a.amount);
    
    setStatisticsData(data);
  }, [expenses]);
  
  // 自定义Tooltip
  const CustomTooltip = ({ active, payload }: any) => {
    if (active && payload && payload.length) {
      return (
        <div className="bg-white dark:bg-gray-800 p-3 rounded-lg shadow-md border border-gray-100 dark:border-gray-700">
          <p className="font-medium">{CATEGORY_CONFIG[payload[0].name as keyof typeof CATEGORY_CONFIG]?.name}</p>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            ¥{payload[0].value.toFixed(2)} ({payload[0].payload.percentage.toFixed(1)}%)
          </p>
        </div>
      );
    }
    return null;
  };
  
  // 自定义Legend
  const CustomLegend = ({ payload }: any) => {
    if (payload && payload.length) {
      return (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2 mt-4">
          {payload.map((entry: any, index: number) => {
            const category = entry.payload.category as keyof typeof CATEGORY_CONFIG;
            return (
              <div key={`legend-${index}`} className="flex items-center text-sm">
                <div
                  className={`w-3 h-3 rounded-full mr-2 ${
                    CATEGORY_CONFIG[category]?.color
                  }`}
                  style={{ backgroundColor: CATEGORY_CONFIG[category]?.color.replace('bg-', '') }}
                />
                <span className="text-gray-700 dark:text-gray-300">
                  {CATEGORY_CONFIG[category]?.name}
                </span>
                <span className="ml-2 text-gray-500 dark:text-gray-400">
                  ({entry.payload.percentage.toFixed(1)}%)
                </span>
              </div>
            );
          })}
        </div>
      );
    }
    return null;
  };
  
  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl p-5 shadow-md border border-gray-100 dark:border-gray-700">
      <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-4">消费统计</h2>
      
      {statisticsData.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-10 text-center">
          <div className="bg-gray-100 dark:bg-gray-700 p-3 rounded-full mb-3">
            <i className="fas fa-chart-pie text-gray-400"></i>
          </div>
          <p className="text-gray-500 dark:text-gray-400">暂无数据</p>
        </div>
      ) : (
        <>
          <div className="mb-6">
            <div className="flex justify-between items-end">
              <div>
                <h3 className="text-sm text-gray-500 dark:text-gray-400">总消费</h3>
                <p className="text-3xl font-bold text-gray-900 dark:text-white">¥{totalAmount.toFixed(2)}</p>
              </div>
              <div className="text-right">
                <p className="text-sm text-gray-500 dark:text-gray-400">记录数量</p>
                <p className="text-lg font-semibold text-gray-900 dark:text-white">{expenses.length}</p>
              </div>
            </div>
          </div>
          
          <div className="flex flex-col md:flex-row items-center">
            <div className="w-full md:w-1/2 h-64">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={statisticsData}
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={80}
                    paddingAngle={5}
                    dataKey="amount"
                    labelLine={false}
                  >
                    {statisticsData.map((entry, index) => (
                      <Cell
                        key={`cell-${index}`}
                        fill={entry.color.replace('bg-', '')}
                      />
                    ))}
                  </Pie>
                  <Tooltip content={<CustomTooltip />} />
                  <Legend content={<CustomLegend />} />
                </PieChart>
              </ResponsiveContainer>
            </div>
            
            <div className="w-full md:w-1/2 mt-4 md:mt-0">
              <h3 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">类别明细</h3>
              <div className="space-y-3">
                {statisticsData.map((item) => (
                  <div key={item.category} className="flex items-center justify-between">
                    <div className="flex items-center">
                      <div
                        className={`w-3 h-3 rounded-full mr-2 ${item.color}`}
                      />
                      <span className="text-sm text-gray-700 dark:text-gray-300">
                        {CATEGORY_CONFIG[item.category as keyof typeof CATEGORY_CONFIG]?.name}
                      </span>
                    </div>
                    <div className="text-right">
                      <p className="text-sm font-medium text-gray-900 dark:text-white">¥{item.amount.toFixed(2)}</p>
                      <p className="text-xs text-gray-500 dark:text-gray-400">{item.percentage.toFixed(1)}%</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default Statistics;